package com.chookss.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.chookss.R;
import com.chookss.tools.MyToast;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.ScreenshotUtil;
import com.chookss.tools.Utils;
import com.chookss.view.listener.ShareDialogListener;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


public class ShareQrCodeDialog extends BaseDialog {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.ivQrcode)
    ImageView ivQrcode;
    @BindView(R.id.tvDown)
    TextView tvDown;
    @BindView(R.id.llQrCode)
    LinearLayout llQrCode;
    private Activity context;
    private String url;
    private ShareDialogListener listener = null;

    public void ShareDialogListener(@NonNull Context context) {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_share_qrcode;
    }

    @Override
    protected void init(View view) {
        initCenter(0.3f);
        tvDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestSTORAGE();

            }
        });
    }
    private void initView(String url) {
        Observable.just(url).map(new Function<String, Bitmap>() {
            @Override
            public Bitmap apply(String s) throws Exception {
                return setQrImage(url, Utils.dip2px(context, 180));
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bitmap>() {
                    @Override
                    public void accept(Bitmap bitmap) throws Exception {
                        try {
                            Glide.with(context).load(bitmap).into(ivQrcode);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private Bitmap setQrImage(String text, int size) {

        try {
            Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.MARGIN, 0); // 设置白边
            /*
             * 设置容错级别，默认为ErrorCorrectionLevel.L
             * 因为中间加入logo所以建议你把容错级别调至H,否则可能会出现识别不了
             */
//            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            BitMatrix bitMatrix = new QRCodeWriter().encode(text,
                    BarcodeFormat.QR_CODE, size, size, hints);
            int[] pixels = new int[size * size];
            // 两个for循环是图片横列扫描的结果
            for (int y = 0; y < size; y++) {
                for (int x = 0; x < size; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * size + x] = 0xff000000;
                    } else {
                        pixels[y * size + x] = 0xffffffff;
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(size, size,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, size, 0, 0, size, size);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void requestSTORAGE() {
        XXPermissions.with(context)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            listener.onClick();
                            dismiss();
                            tvDown.setVisibility(View.GONE);
                            Observable.timer(300, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new Consumer<Long>() {
                                        @Override
                                        public void accept(Long aLong) {
                                            ScreenshotUtil.saveScreenshotFromActivity(context,llQrCode);
                                        }
                                    });

                        } else {
                            MyToast.show("存储未被授权，请先去权限设置里面授权");
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(context, denied, quick);
                    }
                });
    }

    public ShareQrCodeDialog(@NonNull Activity context, String title, String url, ShareDialogListener listener) {
        super(context);
        this.context = context;
        this.listener = listener;
        this.url = url;
        tvTitle.setText(title);
        initView(url);
    }


}